// 获取DOM元素
const maxWidthInput = document.getElementById('maxWidth');
const addToWhitelistBtn = document.getElementById('addToWhitelist');
const addToOptimizeListBtn = document.getElementById('addToOptimizeList');

// 获取模式切换开关
const modeToggle = document.getElementById('modeToggle');

// 保存设置到storage
const saveSettings = async (maxWidth) => {
    const mode = modeToggle.checked ? 'selective' : 'global';
    
    // 获取当前页面的白名单和优化名单状态
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tabs[0]) return;

    const currentUrl = tabs[0].url;
    const result = await chrome.storage.sync.get(['whitelist', 'optimizeList']);
    const inWhitelist = (result.whitelist || []).some(item => item.url === currentUrl);
    const inOptimizeList = (result.optimizeList || []).some(item => item.url === currentUrl);

    // 保存设置
    await chrome.storage.sync.set({
        mode: mode,
        enabled: true,
        maxWidth: maxWidth
    });

    // 确定是否应该启用优化
    let shouldEnable = false;
    if (!inWhitelist) { // 如果不在白名单中
        if (mode === 'global') {
            shouldEnable = true;
        } else if (mode === 'selective') {
            shouldEnable = inOptimizeList;
        }
    }

    // 通知当前标签页更新设置
    chrome.tabs.sendMessage(tabs[0].id, {
        type: 'TOGGLE_OPTIMIZATION',
        mode: mode,
        enabled: shouldEnable,
        maxWidth: maxWidth
    });
};

// 加载保存的设置
const loadSettings = () => {
    chrome.storage.sync.get(['mode', 'maxWidth', 'whitelist', 'optimizeList'], (result) => {
        // 设置模式
        modeToggle.checked = result.mode === 'selective';
        
        // 设置最大宽度
        if (result.maxWidth) {
            maxWidthInput.value = result.maxWidth;
        }

        // 检查当前网站状态
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            if (tabs[0] && tabs[0].url) {
                const currentUrl = tabs[0].url;
                
                // 检查白名单
                const whitelist = result.whitelist || [];
                if (isUrlInList(currentUrl, whitelist)) {
                    addToWhitelistBtn.textContent = '从白名单移除';
                    addToWhitelistBtn.dataset.inWhitelist = 'true';
                } else {
                    addToWhitelistBtn.textContent = '添加到白名单';
                    addToWhitelistBtn.dataset.inWhitelist = 'false';
                }
                
                // 检查优化名单
                const optimizeList = result.optimizeList || [];
                if (isUrlInList(currentUrl, optimizeList)) {
                    addToOptimizeListBtn.textContent = '从优化名单移除';
                    addToOptimizeListBtn.dataset.inOptimizeList = 'true';
                } else {
                    addToOptimizeListBtn.textContent = '添加到优化名单';
                    addToOptimizeListBtn.dataset.inOptimizeList = 'false';
                }
            }
        });
    });
};

// 修改模式切换监听函数
modeToggle.addEventListener('change', async () => {
    await saveSettings(parseInt(maxWidthInput.value, 10));
    // 获取当前标签页并刷新
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    if (tabs[0]) {
        chrome.tabs.reload(tabs[0].id);
    }
});

// 处理最大宽度变更
maxWidthInput.addEventListener('change', (e) => {
    const maxWidth = parseInt(e.target.value, 10);
    if (maxWidth >= 500 && maxWidth <= 2000) {
        saveSettings(maxWidth);
    } else {
        // 如果输入的值超出范围，重置为默认值
        e.target.value = 1100;
        saveSettings(1100);
    }
});

// 创建列表项
function createListItem(item, type) {
    const date = new Date(item.timestamp).toLocaleDateString();
    return `
        <div class="list-item" data-url="${item.url}">
            <div class="item-info">
                <div class="item-url-container">
                    <span class="item-url">${item.url}</span>
                    <input type="text" class="edit-input" value="${item.url}" style="display: none;">
                </div>
                <div class="item-date">${date}</div>
            </div>
            <div class="item-actions">
                <button class="action-btn edit-btn" data-type="${type}" data-url="${item.url}">
                    <svg viewBox="0 0 24 24">
                        <path fill="currentColor" d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
                    </svg>
                </button>
                <button class="action-btn remove-btn" data-type="${type}" data-url="${item.url}">
                    <svg viewBox="0 0 24 24">
                        <path fill="currentColor" d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                    </svg>
                </button>
            </div>
        </div>
    `;
}

// 修改 handleEdit 函数
async function handleEdit(type, oldUrl, newUrl) {
    if (!newUrl || oldUrl === newUrl) return;

    try {
        // 获取当前列表
        const result = await chrome.storage.sync.get([type]);
        let list = result[type] || [];

        // 查找并更新项目
        const index = list.findIndex(item => item.url === oldUrl);
        if (index !== -1) {
            list[index] = {
                ...list[index],
                url: newUrl,
                timestamp: Date.now()
            };

            // 保存更新后的列表
            await chrome.storage.sync.set({ [type]: list });

            // 重新加载列表显示
            await loadLists();

            // 获取当前标签页并刷新
            const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
            if (tabs[0]) {
                chrome.tabs.reload(tabs[0].id);
            }
        }
    } catch (error) {
        console.error('Error updating URL:', error);
    }
}

// 添加编辑按钮事件监听
function setupEditListeners() {
    document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const listItem = e.target.closest('.list-item');
            const urlContainer = listItem.querySelector('.item-url-container');
            const urlSpan = urlContainer.querySelector('.item-url');
            const urlInput = urlContainer.querySelector('.edit-input');
            const type = e.target.dataset.type;
            const originalUrl = e.target.dataset.url;

            // 切换显示/编辑模式
            if (urlSpan.style.display !== 'none') {
                // 进入编辑模式
                urlSpan.style.display = 'none';
                urlInput.style.display = 'block';
                urlInput.focus();
                
                // 添加保存事件监听
                urlInput.addEventListener('keypress', async (event) => {
                    if (event.key === 'Enter') {
                        const newUrl = urlInput.value.trim();
                        await handleEdit(type, originalUrl, newUrl);
                        
                        // 恢复显示模式
                        urlSpan.style.display = 'block';
                        urlInput.style.display = 'none';
                    }
                });

                // 添加失焦保存
                urlInput.addEventListener('blur', async () => {
                    const newUrl = urlInput.value.trim();
                    await handleEdit(type, originalUrl, newUrl);
                    
                    // 恢复显示模式
                    urlSpan.style.display = 'block';
                    urlInput.style.display = 'none';
                });
            }
        });
    });
}

// 合并 loadLists 和 updateLists 函数
async function loadLists() {
    try {
        const result = await chrome.storage.sync.get(['optimizeList', 'whitelist']);
        const optimizeList = result.optimizeList || [];
        const whitelist = result.whitelist || [];

        // 更新优化名单
        const optimizeListEl = document.querySelector('.optimize-list');
        document.querySelector('.optimize-count').textContent = optimizeList.length;
        
        if (optimizeList.length === 0) {
            optimizeListEl.innerHTML = '<div class="empty-list">暂无记录</div>';
        } else {
            optimizeListEl.innerHTML = optimizeList.map(item => createListItem(item, 'optimizeList')).join('');
        }

        // 更新白名单
        const whitelistEl = document.querySelector('.whitelist-list');
        document.querySelector('.whitelist-count').textContent = whitelist.length;
        
        if (whitelist.length === 0) {
            whitelistEl.innerHTML = '<div class="empty-list">暂无记录</div>';
        } else {
            whitelistEl.innerHTML = whitelist.map(item => createListItem(item, 'whitelist')).join('');
        }

        // 设置编辑和删除按钮的事件监听
        setupEditListeners();
        setupDeleteListeners();
    } catch (error) {
        console.error('Error loading lists:', error);
    }
}

// 添加删除按钮事件监听器设置函数
function setupDeleteListeners() {
    document.querySelectorAll('.remove-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            const button = e.currentTarget;
            const type = button.dataset.type;
            const url = button.dataset.url;
            await handleRemove(type, url);
        });
    });
}

// 修改 handleRemove 函数
const handleRemove = async (type, url) => {
    try {
        const storageKey = type === 'optimizeList' ? 'optimizeList' : 'whitelist';
        const result = await chrome.storage.sync.get([storageKey]);
        const list = result[storageKey] || [];
        const updatedList = list.filter(item => item.url !== url);
        
        await chrome.storage.sync.set({ [storageKey]: updatedList });
        
        // 更新按钮状态
        if (type === 'optimizeList') {
            addToOptimizeListBtn.textContent = '添加到优化名单';
            addToOptimizeListBtn.dataset.inOptimizeList = 'false';
        } else {
            addToWhitelistBtn.textContent = '添加到白名单';
            addToWhitelistBtn.dataset.inWhitelist = 'false';
        }
        
        // 重新加载列表
        await loadLists();
        await saveSettings(parseInt(maxWidthInput.value, 10));

        // 获取当前标签页并刷新
        const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
        if (tabs[0]) {
            chrome.tabs.reload(tabs[0].id);
        }
    } catch (error) {
        console.error('Error removing item:', error);
    }
};

// 添加 URL 匹配函数
function matchUrl(pattern, url) {
    // 转换通配符为正则表达式
    const regexPattern = pattern
        .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // 转义特殊字符
        .replace(/\*/g, '.*'); // 将 * 转换为 .*
    const regex = new RegExp(`^${regexPattern}`);
    return regex.test(url);
}

// 修改检查URL是否在列表中的逻辑
function isUrlInList(url, list) {
    return list.some(item => matchUrl(item.url, url));
}

// 修改 handleListButtonClick 函数
const handleListButtonClick = async (type) => {
    try {
        const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
        if (!tabs[0] || !tabs[0].url) return;

        const currentUrl = tabs[0].url;
        const currentTitle = tabs[0].title;
        const storageKey = type === 'optimize' ? 'optimizeList' : 'whitelist';
        
        const result = await chrome.storage.sync.get([storageKey]);
        let list = result[storageKey] || [];
        
        // 使用新的匹配函数检查URL
        const inList = isUrlInList(currentUrl, list);
        const btn = type === 'optimize' ? addToOptimizeListBtn : addToWhitelistBtn;

        if (inList) {
            // 移除匹配的项
            list = list.filter(item => !matchUrl(item.url, currentUrl));
            btn.textContent = `添加到${type === 'optimize' ? '优化' : '白'}名单`;
            btn.dataset[type === 'optimize' ? 'inOptimizeList' : 'inWhitelist'] = 'false';
        } else {
            // 添加新项，支持用户输入通配符
            const urlInput = prompt('请输入URL模式 (可使用 * 作为通配符):', currentUrl);
            if (urlInput) {
                list.push({
                    url: urlInput.trim(),
                    title: currentTitle,
                    timestamp: Date.now()
                });
                btn.textContent = `从${type === 'optimize' ? '优化' : '白'}名单移除`;
                btn.dataset[type === 'optimize' ? 'inOptimizeList' : 'inWhitelist'] = 'true';
            }
        }

        await chrome.storage.sync.set({ [storageKey]: list });
        await loadLists();
        await saveSettings(parseInt(maxWidthInput.value, 10));

        // 刷新当前标签页
        if (tabs[0]) {
            chrome.tabs.reload(tabs[0].id);
        }
    } catch (error) {
        console.error('Error handling list button click:', error);
    }
};

// 修改优化名单按钮点击事件
addToOptimizeListBtn.addEventListener('click', () => handleListButtonClick('optimize'));
addToWhitelistBtn.addEventListener('click', () => handleListButtonClick('whitelist'));

// 添加名单列表样式
const style = document.createElement('style');
style.textContent = `
    .lists-container {
        margin-top: 20px;
        border-top: 1px solid #e0e0e0;
        padding-top: 20px;
    }

    .lists-section {
        margin-bottom: 20px;
    }

    .list-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
    }

    .list-header h2 {
        font-size: 14px;
        margin: 0;
        color: #202124;
    }

    .list-count {
        background: #e8f0fe;
        color: #1a73e8;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
    }

    .list-item {
        padding: 8px 12px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #f8f9fa;
        border-radius: 6px;
        margin-bottom: 6px;
        font-size: 12px;
        transition: all 0.2s ease;
    }

    .list-item:hover {
        background: #f1f3f4;
    }

    .item-info {
        flex: 1;
        min-width: 0;
        margin-right: 12px;
    }

    .item-title {
        font-weight: 500;
        margin-bottom: 2px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .item-url-container {
        position: relative;
    }

    .item-url {
        color: #5f6368;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .item-url-full {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        z-index: 1;
    }

    .url-edit {
        width: 100%;
        padding: 2px 4px;
        border: 1px solid #dadce0;
        border-radius: 4px;
        font-size: 12px;
        color: #5f6368;
        background: white;
    }

    .url-edit:focus {
        outline: none;
        border-color: #1a73e8;
        box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
    }

    .item-actions {
        display: flex;
        gap: 4px;
        align-items: center;
    }

    .action-btn {
        width: 24px;
        height: 24px;
        padding: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.15s ease;
        background: transparent;
        opacity: 0.6;
    }

    .action-btn:hover {
        opacity: 1;
        background: rgba(0, 0, 0, 0.05);
    }

    .edit-btn {
        color: #1a73e8;
    }

    .remove-btn {
        color: #dc3545;
    }

    .list-item:hover .action-btn {
        opacity: 0.8;
    }

    .action-btn svg {
        width: 16px;
        height: 16px;
        pointer-events: none; /* 防止SVG内部元素触发事件 */
    }

    .empty-list {
        text-align: center;
        padding: 8px;
        color: #666;
        font-style: italic;
        background: #f8f9fa;
        border-radius: 6px;
        font-size: 12px;
    }

    /* 优化滚动区域 */
    .lists-container {
        max-height: 200px;
        overflow-y: auto;
        margin-bottom: 0;
        scrollbar-width: thin;
        scrollbar-color: #dadce0 transparent;
    }

    .lists-container::-webkit-scrollbar {
        width: 6px;
    }

    .lists-container::-webkit-scrollbar-track {
        background: transparent;
    }

    .lists-container::-webkit-scrollbar-thumb {
        background-color: #dadce0;
        border-radius: 3px;
    }

    .lists-container::-webkit-scrollbar-thumb:hover {
        background-color: #bdc1c6;
    }
`;

// 添加清空名单功能
async function clearList(type) {
    try {
        // 显示确认对话框
        const listType = type === 'optimizeList' ? '优化名单' : '白名单';
        const confirmed = confirm(`确定要清空${listType}吗？此操作不可恢复。`);
        
        if (!confirmed) {
            return;
        }

        // 清空指定名单
        await chrome.storage.sync.set({ [type]: [] });
        
        // 更新按钮状态
        if (type === 'optimizeList') {
            addToOptimizeListBtn.textContent = '添加到优化名单';
            addToOptimizeListBtn.dataset.inOptimizeList = 'false';
        } else {
            addToWhitelistBtn.textContent = '添加到白名单';
            addToWhitelistBtn.dataset.inWhitelist = 'false';
        }
        
        // 重新加载列表
        await loadLists();
        await saveSettings(parseInt(maxWidthInput.value, 10));

        // 获取当前标签页并刷新
        const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
        if (tabs[0]) {
            chrome.tabs.reload(tabs[0].id);
        }
    } catch (error) {
        console.error('Error clearing list:', error);
    }
}

// 设置清空按钮的事件监听
function setupClearListeners() {
    document.querySelectorAll('.clear-list-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            const type = e.currentTarget.dataset.type;
            await clearList(type);
        });
    });
}

// 初始化
document.addEventListener('DOMContentLoaded', async () => {
    await loadLists();
    loadSettings();
    setupClearListeners();
});

// 错误处理
const handleError = (error) => {
    console.error('Width Optimizer Error:', error);
    // 可以在这里添加用户提示UI
};

// 添加错误处理
window.onerror = function(message, source, lineno, colno, error) {
    handleError(error);
    return true;
};